import CryptoJS from "crypto-js";

const DEFAULTKEY = "olacvujkeddot832";
const USERKEY = "iokwscvbfrddls03";
const LIBRARY =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

function encrypt(word: any, keyStr: string | null): any {
  const _word = JSON.stringify(word) || "";
  const _keyStr = keyStr ? keyStr : DEFAULTKEY;
  const _key = CryptoJS.enc.Utf8.parse(_keyStr);
  const _srcs = CryptoJS.enc.Utf8.parse(_word);
  const _encrypted = CryptoJS.AES.encrypt(_srcs, _key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return _encrypted.toString();
}
function decrypt(word: any, keyStr: string | null): any {
  try {
    const _keyStr = keyStr ? keyStr : DEFAULTKEY;
    const _word = word || "";
    const _key = CryptoJS.enc.Utf8.parse(_keyStr);
    const _decrypt = CryptoJS.AES.decrypt(_word, _key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    return JSON.parse(CryptoJS.enc.Utf8.stringify(_decrypt).toString());
  } catch (error) {
    // 解密失败，跳转到错误页面
    return error;
  }
}

export { encrypt, decrypt, DEFAULTKEY, USERKEY, LIBRARY };
